<template>
    <div class="read-page" :class="[readSetting.background,readSetting.fontsize]">
        <img src="@/assets/img/icon/mark.png" class="markIcon" v-if="isMark" alt="">
        <div class="read-top clearfix">
            <i class="left" @click="$router.go(-1)"></i>
            <span class="right">{{book.bookName}}</span>
        </div>
        <div class="operate clearfix" ref="mainContent" id="content"  @click.stop="toolShow=true">
            <div class="wordMain"  id="mianContent">
                <p v-for="(item,index) in contentList" :key="'index' + index">
                    <template  v-if="index<150 && item.type==='text'">
                      &emsp;&emsp;{{item.content}}
                    </template>
                     <template  v-if="item.type==='image'">
                      <img :src="`data:image/png;base64,${item.content}`" style="width:100%;">
                    </template>
                    <br>
                </p>
            </div>
        </div>
        <div class="read-bottom">
            <!-- <span>左侧点击上一页</span> -->
            <i>{{pageNum}}/{{totalPages}}</i>
            <!-- <span>右侧点击下一页</span> -->
        </div>

        <div class="tool-mask" v-show="toolShow||isTips||isResult" @click.stop="toolAllClose"></div>
        <transition name='slideup'>
            <div class="tool-box" v-show="toolShow">
                <!-- <div class="tools tool-page"></div> -->
                <div class="tools tool-bookmark" @click="addBookMark">书签</div>
                <div class="tools tool-fontsize" @click="tool_FS=true">字号</div>
                <div class="tools tool-background" @click="tool_BG=true">背景</div>
            </div>
        </transition>

        <transition name='slideup'>
            <div class="tool-box" v-show="toolShow&&tool_FS">
                <!-- <div class="tools tool-page"></div> -->
                <div class="fontsize small" :class="{'active':readSetting.fontsize=='fs_small'}" @click="setProperty('fontsize','fs_small')">小</div>
                <div class="fontsize normal" :class="{'active':readSetting.fontsize=='fs_normal'}" @click="setProperty('fontsize','fs_normal')">中</div>
                <div class="fontsize large" :class="{'active':readSetting.fontsize=='fs_large'}" @click="setProperty('fontsize','fs_large')">大</div>
            </div>
        </transition>

        <transition name='slideup'>
            <div class="tool-box" v-show="toolShow&&tool_BG">
                <!-- <div class="tools tool-page"></div> -->
                <div class="background normal" :class="{'active':readSetting.background=='normal'}" @click="setProperty('background','normal')"></div>
                <div class="background orange" :class="{'active':readSetting.background=='orange'}" @click="setProperty('background','orange')"></div>
                <div class="background green" :class="{'active':readSetting.background=='green'}" @click="setProperty('background','green')"></div>
                <div class="background black" :class="{'active':readSetting.background=='black'}" @click="setProperty('background','black')"></div>
            </div>
        </transition>

        <transition name="fade">
            <div class="tipsBox" v-if="isTips">
                <div class="readTipsTit">
                     <span class="tipSpan">免费内容已经浏览完毕</span>
                </div>
                <div class="readTipsInfo">
                    <template v-if="cardNum<=0">
                        您目前没有书券，无法进行兑换
                    </template>
                    <template v-else>
                         消耗 1 张书券来兑换这本书吗？
                    </template>
                </div>
                <div class="readTipsSubInfo">
                     <template v-if="cardNum<=0">
                        请购买书券后兑换
                    </template>
                    <template v-else>
                       您当前还剩 {{cardNum}} 张书券
                    </template>
                </div>
                <div class="tipsBtnBox">
                    <template v-if="cardNum<=0">
                        <div class="btn" @click="cancel">取消</div>
                        <div class="btn active" @click="goToBuyCard">购买书券</div>
                    </template>
                    <template v-else>
                        <div class="btn"  @click="cancel">取消</div>
                        <div class="btn active" @click="exchangeBook">确认</div>
                    </template>
                </div>
            </div>
            <div class="tipsBox" v-if="noContent">
                <div class="readTipsInfo">
                     <span class="tipSpan">该书籍暂无内容</span>
                </div>
                <div class="tipsBtnBox">
                        <div class="btn active" @click="noContent = false">确认</div>
                </div>
            </div>
        </transition>

        <transition name='fade'>
            <div class="resultBox" v-show="isResult">
                <div class="resultSuccess" v-if="isPaySuccess">
                    兑换成功
                </div>
                <div class="resultError" v-if="!isPaySuccess">
                    兑换失败
                </div>
                <div class="resultMsg">
                    <template v-if="isPaySuccess">
                        恭喜！您可以完整浏览本书的内容了
                    </template>
                    <template v-else>
                       对不起，兑换失败，请刷新后重试
                    </template>
                </div>
                <div class="resultTip" v-if="isPaySuccess"><span>如果无法正常浏览，请退出快乐读书吧后重试</span></div>
                <div class="confirm" @click="()=> isResult=false">确定</div>
            </div>
        </transition>
    </div>
</template>

<script>
import { axGet,axPost } from '@/api/index'
export default {
    data(){
        return {
            book:{
                bookName:"这里是标题"
            },
            readSetting:{
                bookmark: 0,
                fontsize: 'fs_normal',
                background: 'normal',
            },
            book:{},
            user:this.$parent.myInfo,
            bookid:this.$route.query.bookid,
            // bookid:'36344754-E6C7-E911-80BA-801844F2C930',
            cardNum:0,                          //持有的书券的数量
            pageNum:1,
            totalPages:1,
            toolShow:false,
            isTips:false,
            isResult:false,
            noContent:false,
            tool_FS:false,
            tool_BG:false,
            isPaySuccess:true,
            contentList:[],
            offsetHeight:0, //页面总高度
            clientHeight:0,// 可视高度
            scrollHeight:0, //当前滚动高度
            isMark:false,//标签是否显示
            markPageNum:0, //标签所在页
            canRead:true//有无权限继续阅读
        }
    },
    mounted(){
        this.init();
        this.book = JSON.parse(sessionStorage.getItem("thisBook")) 
        this.$nextTick(()=>{
            this.clientHeight = document.getElementById('content').clientHeight
            this.$refs.mainContent.addEventListener('scroll',this.handleScroll)
            this.$refs.mainContent.addEventListener('touchend',this.debounce(this.moveScroll, 100))
        })
    },
     beforeDestroy() {
      console.log('--------组件即将销毁')
      this.SaveBookProgress()
      window.removeEventListener('scroll', this.handleScroll);
    },
 
    methods:{
        init(){
            this.getBookContent();
            this.getBookMark();
            this.getMyCard();
        },
        debounce(func, wait) {
            let timeout;
            return function () {
                let context = this;
                let args = arguments;
                if (timeout) clearTimeout(timeout);
                
                timeout = setTimeout(() => {
                    func.apply(context, args)
                }, wait);
            }
        },
        moveScroll(){
            //下一章
               if(this.scrollHeight >= this.offsetHeight -this.clientHeight){
                        if(this.canRead){
                            this.pageNum = this.pageNum+1
                        }
                        this.getBookContent()
                     console.log('你已经滑到底部了')
               }
               
            //上一章
            if(this.scrollHeight <=0){
                if(this.pageNum >1){
                        this.pageNum =this.pageNum -1
                        this.getBookContent()
                }
                 console.log('你已经滑到顶部了')
            }
        },
        handleScroll(){
               this.scrollHeight = document.getElementById('content').scrollTop
               this.scrollHeight = document.getElementById('content').scrollTop
               this.offsetHeight = document.getElementById('mianContent').offsetHeight 
               console.log( document.getElementById('content').scrollTop)
        },
        async SaveBookProgress(){
             let res =  axPost('SaveBookProgress', {userId:this.user.UserId,bookId:this.bookid,fontSize:this.readSetting.fontsize,description:'',chapter:this.pageNum,attributes:this.scrollHeight})
        },
        goToBuyCard(){
            this.$router.push('/buybook')
        },
        cancel(){
            this.isTips= false
        },
        async GetBookProgress(){
             let res = await axGet('GetBookProgress', {userId:this.user.UserId,bookId:this.bookid})
             if(res.ResultCode===1){
                 this.scrollHeight = res.Value.attributes
                 this.pageNum =res.Value.chapter
                 this.getBookContent('flag')
                 this.readSetting.fontsize = res.Value.fontSize
             }
             console.log('----->>>>',res)
        },
        async exchangeBook(){
             let res = await  axPost('UseVoucher', {userId:this.user.UserId,bookId:this.bookid})
             this.isResult =true
             if(res.ResultCode === 1){
                 this.isTips = false
                 this.isPaySuccess =true
             }else{
                 this.isTips = false
                 this.isPaySuccess =false
             }
        },
        async addBookMark(){
             let res = await axPost('AddBookMark', {userId:this.user.UserId,bookId:this.bookid,fontSize:this.readSetting.fontsize,description:'',chapter:this.pageNum,attributes:this.scrollHeight})
             if(res.ResultCode===1){
                this.markPageNum = this.pageNum
                this.isMark =true
             }
        },
        async getMyCard(){
            let res = await axGet('GetMyVoucher', {userId:this.user.UserId,})
            this.cardNum = res.Value;
        },
        async getBookMark(){
            // cmd:GetBookMarkList
            // 参数:
            // userId
            // bookId
            // pageIndex
            // pageSize
            let res = await axGet('GetBookMarkList', {userId:this.user.UserId,bookId:this.bookid,pageIndex:1,pageSize:1})
            if(res.ResultCode===1){
                if(res.Value.list.length>0){
                    
                    const data =res.Value.list[0]
                     this.scrollHeight =data.attributes
                     this.pageNum =data.chapter
                     this.markPageNum =data.chapter
                     this.getBookContent('flag')
                     this.readSetting.fontsize = data.fontSize
                   
                }else{
                    this.GetBookProgress()
                }
            }
            console.log(res,"获取的书签列表")
        },
        async getBookContent(flag){
            //是否是标签页
            if(this.pageNum === this.markPageNum){
                this.isMark =true
            }else{
                this.isMark =false
            }
            
            let res = await axGet('GetBookReadingContent', {userId:this.user.UserId,bookId:this.bookid,pageIndex:this.pageNum})
            if(res.ResultCode == 1){
                this.canRead =true
                this.contentList = res.Value.list
                this.totalPages = res.Value.totalRecords
                this.pageNum =res.Value.pageIndex
                if(flag){
                    setTimeout(() => {
                       document.getElementById('content').scrollTop = this.scrollHeight 
                    }, 60);
                }else{
                   document.getElementById('content').scrollTop = 5
               
                }
                
                // console.log(this.contentList,"this.contentList")
            }else if(res.ResultCode == -1){
                
                this.noContent =true
            }else{
                this.isTips = true;
                this.canRead =false
                this.pageNum =1
            }
            // console.log(res,"书本内容")
            // cmd:GetBookReadingContent
            // 参数：
            // userId
            // bookId
            // chapter/////章节
        },
        toolAllClose(){
            this.toolShow = false;
            this.isTips = false;
            this.isResult = false;
            this.tool_FS = false;
            this.tool_BG = false;
        },
        setProperty(propertyName,propertyVal){
            this.readSetting[propertyName] = propertyVal;
        },
    }
}
</script>

<style lang='scss' scoped>
.read-page{
    height: 100%;
    box-sizing: border-box;
    padding: 1rem 16px;
    position: relative;
    overflow: hidden;
    background: #f7f7f7;
    font-size: .36rem;
    transition: .5s all;
    .markIcon{
            position: fixed;
            top: 0;
            right: .3rem;
            width: .6rem;
            z-index: 999;
    }
    &.normal{
        background: #f7f7f7;
    }
    &.orange{
        background: #efe0bf;
    }
    &.green{
        background: #cdeac9;
    }
    &.black{
        background: #1c1c1e;
        color: #a8a8a9;
    }
    &.fs_small{
        font-size: .3rem;
    }
    &.fs_normal{
        font-size: .36rem;
    }
    &.fs_large{
        font-size: .42rem;
    }

}
.read-top{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    box-sizing: border-box;
    padding: 0.28rem 16px 0;
    height: 0.9rem;
    font-size: 0.3rem;
    color: #7f7f7f;
    line-height: 0.56rem;
    i{
        width: 0.56rem;
        height: 0.56rem;
        background: url(~@/assets/img/icon/return-r.png) no-repeat 0 0;
        background-size: 100%;
        transition: .5s all;
    }
}
.black .read-top i{
    background: url(~@/assets/img/icon/return-b.png) no-repeat 0 0;
    background-size: 100%;
}
.operate{
    position: absolute;
    top: 0.9rem;
    left: 0;
    width: 100%;
    height: calc(100% - 1.8rem);
    z-index: 5;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
}
.read-bottom{
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    box-sizing: border-box;
    padding: 0 16px;
    height: 0.9rem;
    line-height: 0.9rem;
    font-size: 0.24rem;
    color: #b2b2b2;
    display:-webkit-box;  
	display:-webkit-flex; 
    display: flex;
    -webkit-justify-content: space-between;
	justify-content: space-between;
}
.wordMain{
    line-height: 2em;
    padding: 0 .4rem;
}
.tool-mask{
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,.1);
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
}

.tool-box{
    background: rgba(255,255,255,1);
    border-radius: .35rem .35rem 0 0;
    width: 100%;
    height: 2.3rem;
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 15;
    display: flex;
    justify-content: space-around;
    padding: .45rem .1rem;
    box-sizing: border-box;
    transition: .4s all;
    .tools{
        width: 1.4rem;
        height: 1.4rem;
        border-radius: .25rem;
        background-color: #f3f5f7;
        font-size: .24rem;
        color: #666;
        text-align: center;
        padding-top:.9rem;
        box-sizing: border-box;
        &.tool-bookmark{
            background-image: url(~@/assets/img/icon/bookmark.png);
            background-repeat: no-repeat;
            background-size: 28% auto;
            background-position: center .4rem;
        }
        &.tool-fontsize{
            background-image: url(~@/assets/img/icon/fontsize.png);
            background-repeat: no-repeat;
            background-size: 34% auto;
            background-position: center .4rem;
        }
        &.tool-background{
            background-image: url(~@/assets/img/icon/background.png);
            background-repeat: no-repeat;
            background-size: 32% auto;
            background-position: center .4rem;
        }
    }
    .fontsize{
        width: 2rem;
        height: .8rem;
        background: #f3f5f7;
        border-radius: .4rem;
        font-size: .36rem;
        font-weight: bold;
        color: #666666;
        text-align: center;
        line-height: .8rem;
        margin: .3rem 0;
        &.active{
            background: #02affe;
            color: #FFF;
        }
    }
    .background{
        width: 1.5rem;
        height: .8rem;
        border-radius: .4rem;
        margin: .3rem 0;
        box-sizing: border-box;
        &.normal{
            background: #f7f7f7;
        }
        &.orange{
            background: #efe0bf;
        }
        &.green{
            background: #cdeac9;
        }
        &.black{
            background: #3a3a3c;
        }
        &.active{
            border: .04rem solid #02affe;
        }
    }
}
.black .tool-box{
    background: #2c2c2e;
    .tools{
        background-color: #3a3a3c;
    }
}
.tipsBox{
    width: 6.25rem;
    background: #FFF;
    padding: .6rem .3rem;
    border-radius: .4rem;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    z-index: 2001;
    .readTipsTit{
        font-size: .28rem;
        color: #02affe;
        margin: 0 auto;
        position: relative;
        text-align: center;
        .tipSpan{
            position: relative;
        }
        .tipSpan::after{
            content: '';
            width: .08rem;
            height: .08rem;
            border-radius: .04rem;
            background: #02affe;
            position: absolute;
            top: .16rem;
            left: -.25rem;
        }
        .tipSpan::before{
            content: '';
            width: .08rem;
            height: .08rem;
            border-radius: .04rem;
            background: #02affe;
            position: absolute;
            top: .16rem;
            right: -.25rem;
        }
    }
    .readTipsInfo{
        font-size: .36rem;
        font-weight: bold;
        margin: .2rem 0;
        margin-top: .5rem;
        color: #333333;
        text-align: center;
    }
    .readTipsSubInfo{
        font-size: .28rem;
        color: #666666;
        text-align: center
    }
    .tipsBtnBox{
        text-align: center;
        margin-top: .4rem;
        .btn{
            display: inline-block;
            width: 2.3rem;
            height: .8rem;
            border-radius: .4rem;
            line-height: .8rem;
            background: #e5f7ff;
            color: #02affe;
            margin: 0 .2rem;
            &.active{
                background: #02affe;
                color: #FFF;
            }
        }
    }
}
.resultBox{
    width: 6.25rem;
    background: #FFF;
    padding: .6rem .3rem;
    border-radius: .4rem;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    z-index: 2001;
    .confirm{
        width: 3.2rem;
        height: .8rem;
        border-radius: .4rem;
        background: #02affe;
        font-size: .32rem;
        color: #FFF;
        line-height: .8rem;
        text-align: center;
        margin: 0 auto;
        margin-top: .5rem;
    }
    .resultMsg{
        font-size: .28rem;
        color: #666;
        margin: .4rem auto;
        text-align: center;
    }
    .resultSuccess{
        background: url(~@/assets/img/main/dot-gou.png) no-repeat top center;
        background-size: 1.1rem auto;
        height: 1.8rem;
        padding-top: 1.4rem;
        text-align: center;
        font-size: .36rem;
        line-height: .4rem;
        font-weight: bold;
        color: #02affe;
        box-sizing: border-box;
    }
    .resultError{
        text-align: center;
        font-size: .36rem;
        line-height: .4rem;
        font-weight: bold;
        color: #333;
    }
}
.resultTip{
    text-align: center;
    margin: 0 auto;
    font-size: .24rem;
    span{
        padding: .2rem .3rem;
        border-radius: .1rem;
        background: #F3F5F7;
        color: #BBB; 
    }
}
</style>